package com.aisino.api.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.aisino.api.model.DrugInfoRequest;
import com.aisino.api.service.DrugStandardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 药品相关工具类
 */
public class DrugUtils {
    private static final String NOT_DELETE = "00";
    private static final String DELETED = "01";
    private static final Logger logger = LoggerFactory.getLogger(DrugStandardService.class);
    /**
     * 插入新的药品信息到申请表中
     *
     * @param drugInfo 药品信息
     * @return 药品唯一标识码
     */
    public String insertNewDrug(DrugInfoRequest.DrugInfoData drugInfo, String entityId, String ypwybsm, JdbcTemplate dmJdbcTemplate) {
        //0 审核中 1 正常/审核通过 2 审核不通过
        String ypzt="0";
        if(ypwybsm==null) {
            ypwybsm = IdWorker.getIdStr();
        }else{
            ypzt="1";
        }
        if(StrUtil.isNotEmpty(drugInfo.getYptxm())&&drugInfo.getYptxm().length()<10){
            drugInfo.setYptxm("");
        }

        String sql = "INSERT INTO YGYD_MAIN.DRUG_STANDARDS_REQ " +
                "(YPWYBSM, YPPZWH, YPSSXKCYRMC, YPSCQYMC, YPTYMC, YPSPMC, BZGG, ZJGG, JX, YPZCFL, " +
                "CFYBS, YBMLYP, GCHJKYP, YPFL, YPYXQ, YPYXQDW, DELETE_FLAG, CREATE_TIME, UPDATE_TIME, YPZT,ID,QYID" +
                ",YPTXM,YPBSM,GJYBBM,YPCF,YYJJ,TSRQ,GNZZ,YFYL,YPXZ,BLFS,CCTJ,ZYSX,XHZY,YPTP) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        Object[] params = {
                ypwybsm,
                drugInfo.getYppzwh(),
                drugInfo.getYpssxkcyrmc(),
                drugInfo.getYpscqymc(),
                drugInfo.getYptymc(),
                drugInfo.getYpspmc(),
                drugInfo.getBzgg(),
                drugInfo.getZjgg(),
                drugInfo.getJx(),
                drugInfo.getYpzcfl(),
                drugInfo.getCfybs(),
                drugInfo.getYbmlyp(),
                drugInfo.getGchjkyp(),
                drugInfo.getYpfl(),
                drugInfo.getYpyxq(),
                drugInfo.getYpyxqdw(),
                NOT_DELETE,
                ypzt,
                entityId+drugInfo.getId(),
                entityId,
                drugInfo.getYptxm(),
                drugInfo.getYpbsm(),
                drugInfo.getGjybbm(),
                drugInfo.getYpcf(),
                drugInfo.getYyjj(),
                drugInfo.getTsrq(),
                drugInfo.getGnzz(),
                drugInfo.getYfyl() ,
                drugInfo.getYpxz(),
                drugInfo.getBlfs(),
                drugInfo.getCctj(),
                drugInfo.getZysx(),
                drugInfo.getXhzy(),
                drugInfo.getYptp()
        };

        logger.info("Inserting new drug with YPWYBSM: {}", ypwybsm);
        dmJdbcTemplate.update(sql, params);
        logger.info("Successfully inserted new drug with YPWYBSM: {}", ypwybsm);
        // 如果ypfl有值，则写入药品分类表
        if (StringUtils.hasText(drugInfo.getYpfl())) {
            String typeSql = "INSERT INTO YGYD_MAIN.DRUG_STANDARDS_TYPE " +
                    "(ID, YPWYBSM, YPID, YPFL) VALUES (?, ?, ?, ?)";
            String typeId = IdWorker.getIdStr();
            Object[] typeParams = {
                    typeId,
                    ypwybsm,
                    ypwybsm,
                    drugInfo.getYpfl()
            };
            logger.info("Inserting drug type record with ID: {}", typeId);
            dmJdbcTemplate.update(typeSql, typeParams);
            logger.info("Successfully inserted drug type record with ID: {}", typeId);
        }
        return ypwybsm;
    }


    /**
     * 插入新的药品信息到标准库中
     *
     * @param drugInfo 药品信息
     * @return 药品唯一标识码
     */
    public String insertNewStandardsDrug(Map<String, Object> row, JdbcTemplate dmJdbcTemplate,String ybmlyp) {
//        logger.info("insertNewStandardsDrug: {}", row);
        String bzgg=createBzgg(row.get("FACTOR"),row.get("MIN_UNIT"),row.get("UNIT"));
        String approvalCode = Convert.toStr(row.get("APPROVAL_CODE")).trim().toUpperCase();
        String ypzcfl=getYpzcfl(approvalCode);
        String cfybs=Convert.toStr(row.get("IS_OTC"),"").equals("1")?"2":"1";
        String gjybbm= Convert.toStr(row.get("GOODS_CODE")).trim();
        List<Map<String, Object>> result = dmJdbcTemplate.queryForList("SELECT YPWYBSM FROM YGYD_MAIN.DRUG_STANDARDS WHERE GJYBBM = ?",gjybbm);
        if (!result.isEmpty()) {
            String ypwybsm = (String) result.get(0).get("YPWYBSM");
            return ypwybsm;
        }
        //0 审核中 1 正常/审核通过 2 审核不通过
        String ypzt="1";
        String ypwybsm = IdWorker.getIdStr();

        String sql = "INSERT INTO YGYD_MAIN.DRUG_STANDARDS " +
                "(YPWYBSM, YPPZWH, YPSSXKCYRMC, YPSCQYMC, YPTYMC, YPSPMC, BZGG, ZJGG, JX, YPZCFL, " +
                "CFYBS, YBMLYP, GCHJKYP, YPFL, YPYXQ, YPYXQDW, DELETE_FLAG, CREATE_TIME, UPDATE_TIME, YPZT,ID,QYID" +
                ",YPTXM,YPBSM,GJYBBM,YPCF,YYJJ,TSRQ,GNZZ,YFYL) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?,?,?,?,?,?,?,?,?,?,?)";
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."APPROVAL_CODE" IS '药品批准文号';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."BASE_ID" IS '基础 ID';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."BUSINESS_LICENSE" IS '营业执照';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."COMPANY_NAME_SC" IS '公司名称';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."DRUG_VALIDITY_DATE" IS '药品有效期（月数）';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."FACTOR" IS '最小包装数量';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."GOODS_CODE" IS '药品代码';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."GOODS_NAME" IS '商品名称';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."GOODS_STANDARD_CODE" IS '本位码';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."INDICATION" IS '适应症';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."IS_CHILD_DRUGS" IS '是否儿童用药（1 表示是，0 表示否）';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."IS_OTC" IS '是否非处方药（1 表示是，0 表示否）';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."MARKET_STATE" IS '市场状态';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."MATERIAL_NAME" IS '材料名称';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."MIN_UNIT" IS '最小单位';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."NAME_OR_HOLDER" IS '名称或持有人';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."PRODUCT_CODE" IS '产品代码';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."PRODUCT_INSURANCE_TYPE" IS '产品保险类型';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."PRODUCT_MEDICINE_MODEL" IS '产品药品型号';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."PRODUCT_NAME" IS '产品名称';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."PRODUCT_REMARK" IS '产品备注';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."REALITY_MEDICINE_MODEL" IS '实际药品型号';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."REALITY_OUTLOOK" IS '实际外观';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."REGISTERED_MEDICINE_MODEL" IS '注册药品型号';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."REGISTERED_OUTLOOK" IS '注册外观';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."REGISTERED_PRODUCT_NAME" IS '注册产品名称';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."SUB_PACKAGER" IS '分包装商';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."UNIT" IS '单位';
//        COMMENT ON COLUMN "YGYD_MAIN"."DRUG_MEDICARE_DIRECTORY"."USAGE_DOSAGE" IS '用法用量';

        Object[] params = {
                ypwybsm,
                approvalCode,
                row.get("NAME_OR_HOLDER"),
                row.get("COMPANY_NAME_SC"),
                row.get("REGISTERED_PRODUCT_NAME"),
                row.get("GOODS_NAME"),
                bzgg,
                row.get("REALITY_OUTLOOK"),
                row.get("REGISTERED_MEDICINE_MODEL"),
                ypzcfl,
                cfybs,
//                是否医保名录药品 1=是 2=否
                ybmlyp,
                null,
                null,
                Convert.toInt(row.get("DRUG_VALIDITY_DATE")),
                "M",
                NOT_DELETE,
                ypzt,
                ypwybsm,
                null,
                null,
                null,
                gjybbm,
                null,
                null,
                null,
                row.get("INDICATION"),
                row.get("USAGE_DOSAGE")
        };

        logger.info("Inserting insertNewStandardsDrug with YPWYBSM: {}", ypwybsm);
        dmJdbcTemplate.update(sql, params);
        return ypwybsm;
    }

    /**
     * 通过批准文号分析药品注册分类
     * @param approvalCode
     * @return
     */
    private String getYpzcfl(Object approvalCode) {
//        1	中药
//        2	化学药
//        3	生物制品
        if (approvalCode.toString().indexOf("Z")!=-1) {
            return "1";
        } else if (approvalCode.toString().indexOf("H")!=-1) {
            return "2";
        } else{
            return "3";
        }
    }

    private String createBzgg(Object factor, Object minUnit, Object unit) {
        return factor + "" + minUnit + "/" + unit;
    }

}

